package com.grass.cropTradingCenter.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.grass.cropTradingCenter.common.OutputException;
import com.grass.cropTradingCenter.domain.repository.OrderRepository;
import com.grass.cropTradingCenter.mapper.GoodsMapper;
import com.grass.cropTradingCenter.mapper.MiniUserMapper;
import com.grass.cropTradingCenter.mapper.UserOrderMapper;
import com.grass.cropTradingCenter.pojo.entity.Goods;
import com.grass.cropTradingCenter.pojo.entity.MiniUser;
import com.grass.cropTradingCenter.pojo.entity.UserOrder;
import com.grass.cropTradingCenter.pojo.vo.user.QueryOrderVo;
import com.grass.cropTradingCenter.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderRepositoryImpl implements OrderRepository {
    @Autowired
    UserOrderMapper userOrderMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    MiniUserMapper userMapper;


    @Override
    public void save(UserOrder order) {
        userOrderMapper.insert(order);
    }

    @Override
    public void update(UserOrder order) {
        userOrderMapper.updateById(order);
    }

    @Override
    public List<UserOrder> getOrderList(QueryOrderVo vo) {
        LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserOrder::getUserId, SecurityUtils.getUserId());
        queryWrapper.eq(UserOrder::getDelFlag, 0);
        if (vo.getOrderType() != null && vo.getOrderType() != 0) {
            queryWrapper.eq(UserOrder::getOrderType, vo.getOrderType());
        }
        queryWrapper.orderByDesc(UserOrder::getId);
        return userOrderMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmSH(Integer id) {
        UserOrder userOrder = userOrderMapper.selectById(id);
        if (userOrder.getOrderType() == 3) {
            UserOrder order = new UserOrder();
            order.setId(id);
            order.setOrderType(4);
            userOrderMapper.updateById(order);
            // 销量+1
            Goods goods = goodsMapper.selectById(userOrder.getGoodsId());
            goods.setBuyNum(goods.getBuyNum() + 1);
            goodsMapper.updateById(goods);

            // 积分++
            MiniUser user = userMapper.selectById(SecurityUtils.getUserId());
            BigDecimal price = userOrder.getTotalPrice();
            user.setIntegral(price.intValue());
            userMapper.updateById(user);
            return;
        }
        throw new OutputException("状态不符合");
    }
}
